//
//  CZIncomeController.m
//  TCProject
//
//  Created by admin on 16/2/1.
//  Copyright © 2016年 wise-wing. All rights reserved.
//

#import "CZIncomeController.h"
#import "ZDWalletLog.h"
#import "ZDWalletMonth.h"
#import "ZDWalletHeaderView.h"
#import "AccountManager.h"
#import "CZIncomeCell.h"
#import "CAlertView.h"
#import "BankCard.h"
#import "WithdrawController.h"


@interface CZIncomeController ()
@property (nonatomic, strong) NSArray *datas;

@property (strong, nonatomic) BankCard *bankCard;

@property (nonatomic, strong) CAlertView *alertView;

@property (weak, nonatomic) IBOutlet UITextField *secureCodeTextField;
- (IBAction)cancleAlertAction:(id)sender;
- (IBAction)okAlertAction:(id)sender;


@property (weak, nonatomic) IBOutlet UILabel *totalLabel;
@property (weak, nonatomic) IBOutlet UILabel *frostLabel;
@property (weak, nonatomic) IBOutlet UIButton *rechargeButton;
@property (weak, nonatomic) IBOutlet UIButton *addBankButton;

@property (weak, nonatomic) IBOutlet UIButton *unbindButton;

@property (weak, nonatomic) IBOutlet UIView *bankView;
@property (weak, nonatomic) IBOutlet UILabel *bankNameLabel;

@property (weak, nonatomic) IBOutlet UILabel *bankInfoLabel;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
- (IBAction)rechargeAction:(id)sender;
- (IBAction)addBankAction:(id)sender;
- (IBAction)unbindAction:(id)sender;

@property (nonatomic, assign) BOOL unBind;

@end

@implementation CZIncomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configuration];
    
    [self getData];
}

- (void)refreshData
{
    [self getData];
}

- (void)getData
{
    BMRequest *request = [BMRequest requestWithPath:@"getOwnerWallet.htm" contentKey:@"walletLogs"];
    request.params = @{@"id": @([AccountManager sharedInstance].user.ID)};
    [self showHudWithhint:kDefaultMessage];
    [ZDWalletLog postWithRequest:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            NSNumber *accountBalance = response.rawResult[@"accountBalance"];
            NSString *WithdrawalsBalance = response.rawResult[@"WithdrawalsBalance"];
            
            if ([accountBalance isKindOfClass:[NSNull class]]) {
                self.frostLabel.text = [NSString stringWithFormat:@"￥%.1f", 0.f];
            } else {
                self.frostLabel.text = [NSString stringWithFormat:@"￥%.1f", [accountBalance doubleValue]];
            }
            
            if (![BMUtils isEmptyString:WithdrawalsBalance]) {
                self.totalLabel.text = [NSString stringWithFormat:@"￥%@", WithdrawalsBalance];
            } else {
                self.totalLabel.text = [NSString stringWithFormat:@"￥%d", 0];
            }
            [self processData:response.result];
        } else {
            [self showHint:response.msg];
        }
    }];
}

- (void)configuration {
    [self.rechargeButton setBackgroundImage:[UIImage imageWithColor:kGlobalColor] forState:UIControlStateNormal];
    [self.unbindButton setBackgroundImage:[UIImage imageWithColor:kGlobalColor] forState:UIControlStateNormal];
    self.rechargeButton.layer.cornerRadius = self.unbindButton.layer.cornerRadius = 16.f;
    self.rechargeButton.layer.masksToBounds = self.unbindButton.layer.masksToBounds = YES;
    self.bankView.hidden = YES;
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 36.f)];
    bgView.backgroundColor = [UIColor clearColor];
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:14.f];
    label.textColor = kGlobalColor;
    label.text = @"收支明细";
    [bgView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(bgView);
        make.left.mas_equalTo(bgView).offset(15.f);
    }];
    self.tableView.tableHeaderView = bgView;
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 60.f;
    [self.tableView registerClass:[ZDWalletHeaderView class] forHeaderFooterViewReuseIdentifier:@"reuseHeaderIdentifier"];
    [self.tableView registerNib:[UINib nibWithNibName:@"CZIncomeCell" bundle:nil] forCellReuseIdentifier:reuseIdentifier];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.sectionFooterHeight = 0;
}

- (void)checkSecureCodeTask
{
    BMRequest *requeset = [BMRequest requestWithPath:@"checkSureCode.htm"];
    requeset.params = @{@"id": @([AccountManager sharedInstance].user.ID), @"sureCode": _secureCodeTextField.text};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:requeset finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            if (self.unBind) {
                self.unBind = NO;
                [self unBindTask];
            } else {
                WithdrawController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"withdrawVC"];
                vc.price = [[self.totalLabel.text substringFromIndex:1] doubleValue];
                [self showViewController:vc sender:nil];
            }
        } else {
            self.unBind = NO;
            [self showHint:response.msg];
            _secureCodeTextField.text = nil;
        }
    }];
}

- (void)unBindTask
{
    if (!_bankCard) {
        return;
    }
    BMRequest *request = [BMRequest requestWithPath:@"bank/delete.htm"];
    request.params = @{@"id": @(_bankCard.ID)};
    [self showHudWithhint:kDefaultMessage];
    [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
        [self hideHud];
        if (response.status == kResultOK) {
            self.bankView.hidden = YES;
            self.addBankButton.hidden = NO;
            self.bankCard = nil;
        } else {
            [self showHint:@"解绑失败"];
        }
    }];
}

- (void)processData:(NSArray *)data {
    if (data.count == 0)
        return;
    
    NSMutableArray *newData = [NSMutableArray array];
    for (ZDWalletLog *log in data) {
        if (log.type == 5 || log.type == 6) {
            for (int i = 0; i < data.count; i++) {
                if ([(ZDWalletLog *) data[i] type] == 0) {
                    if ([log.orderNum isEqualToString:[data[i] orderNum]]) {
                        for (int j = 0; j < [data[i] serviceLogs].count; j++) {
                            if (log.serviceId == [[data[i] serviceLogs][j] ID]) {
                                if ([[data[i] serviceLogs][j] serviceLogs] == nil) {
                                    [[data[i] serviceLogs][j] setServiceLogs:[NSMutableArray array]];
                                }
                                NSMutableArray *arr = (id) [[data[i] serviceLogs][j] serviceLogs];
                                [arr addObject:log];
                            }
                        }
                    }
                }
            }
        }
    }
    for (ZDWalletLog *log in data) {
        if (log.type != 5 && log.type != 6) {
            if (log.type == 0) {
                for (int i = 0; i < log.serviceLogs.count; i++) {
                    ZDWalletLog *subLog = log.serviceLogs[i];
                    subLog.countMoney += subLog.realsumPrice;
                    if (subLog.serviceLogs != nil) {
                        for (int j = 0; j < subLog.serviceLogs.count; j++) {
                            ZDWalletLog *jLog = subLog.serviceLogs[j];
                            if (jLog.type == 5) {
                                subLog.countMoney -= jLog.money;
                            }
                            if (jLog.type == 6) {
                                subLog.countMoney += jLog.money;
                            }
                        }
                    }
                    log.countMoney += subLog.countMoney;
                }
            }
            [newData addObject:log];
        }
    }
    
    NSMutableArray *array = [NSMutableArray array];
    [newData enumerateObjectsUsingBlock:^(ZDWalletLog *obj, NSUInteger idx, BOOL *stop) {
        if ([obj.name isEqualToString:[array.lastObject name]]) {
            [[array.lastObject incomeDetails] addObject:obj];
        } else {
            ZDWalletMonth *month = [ZDWalletMonth new];
            month.name = obj.name;
            month.incomeDetails = [NSMutableArray array];
            [month.incomeDetails addObject:obj];
            [array addObject:month];
        }
    }];
    
    self.datas = array;
    [self.tableView reloadData];
}

- (CAlertView *)alertView
{
    if (!_alertView) {
        UIView *alert = [[NSBundle mainBundle] loadNibNamed:@"InputSecureCodeView" owner:self options:nil].firstObject;
        alert.layer.cornerRadius = 5.f;
        _alertView = [[CAlertView alloc] initWithView:alert];
    }
    return _alertView;
}

- (IBAction)rechargeAction:(id)sender {
    if (self.bankCard) {
        [self.alertView show];
    } else {
        //        [self showHint:@"请绑定银行卡!"];
        //        [self addBankAction:nil];
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"请先绑定银行卡" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:cancleAction];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"现在去绑定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self addBankAction:nil];
        }];
        [alertVC addAction:okAction];
        //    [cancleAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
        //    [okAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
        [self presentViewController:alertVC animated:YES completion:nil];
    }

}

- (IBAction)addBankAction:(id)sender {
    UIViewController *bindBankVC = [self.storyboard instantiateViewControllerWithIdentifier:@"bindBankVC"];
    [self showViewController:bindBankVC sender:nil];
}

- (IBAction)unbindAction:(id)sender {
    //    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"确定解绑该银行卡号?" preferredStyle:UIAlertControllerStyleAlert];
    //    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    //    [alertVC addAction:cancleAction];
    //    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    [self.alertView show];
    self.unBind = YES;
    //    }];
    //    [alertVC addAction:okAction];
    //    [cancleAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
    //    [okAction setValue:kGlobalColor forKeyPath:@"titleTextColor"];
    //    [self presentViewController:alertVC animated:YES completion:nil];

}
- (IBAction)cancleAlertAction:(id)sender {
     [self.alertView dismissAlertViewWithAnimated:YES];
}

- (IBAction)okAlertAction:(id)sender {
    NSString *code = _secureCodeTextField.text;
    if (code.length < 6 || code.length > 16) {
        [self showHint:@"请输入6-16位安全码"];
        return;
    }
    [self.alertView dismissAlertViewWithAnimated:YES];
    
    [self checkSecureCodeTask];

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self checkBankCard];
}

- (void)setBankCard:(BankCard *)bankCard
{
    _bankCard = bankCard;
    self.bankNameLabel.text = bankCard.bankName;
    NSString *no = [self.bankCard.bankNum substringFromIndex:self.bankCard.bankNum.length - 4];
    self.bankInfoLabel.text = [NSString stringWithFormat:@"尾号%@", no];
}

- (void)checkBankCard
{
    BMRequest *request = [BMRequest requestWithPath:@"getMyBank.htm" contentKey:@"banks"];
    request.params = @{@"ownerId": @([AccountManager sharedInstance].user.ID)};
    [BankCard postWithRequest:request finish:^(BMResponse *response, NSError *error) {
        if (response.status == kResultOK) {
            self.bankView.hidden = NO;
            self.addBankButton.hidden = YES;
            self.bankCard = [response.result firstObject];
        } else if (response.status == 2) {
            self.bankView.hidden = YES;
            self.addBankButton.hidden = NO;
        } else {
            [self showHint:@"获取银行卡信息失败"];
        }
    }];
}



#pragma mark --- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _datas.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    ZDWalletMonth *month = _datas[section];
    if (month.selected) {
        return [_datas[section] incomeDetails].count;
    } else {
        return 0;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 34.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString *reuseHeaderIdentifier = @"reuseHeaderIdentifier";
    weakSelf(self);
    ZDWalletHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:reuseHeaderIdentifier];
    headerView.month = _datas[section];
    headerView.clickAction = ^{
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
    };
    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CZIncomeCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    cell.log = [_datas[indexPath.section] incomeDetails][indexPath.row];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BMBaseModel *detail = [_datas[indexPath.section] incomeDetails][indexPath.row];
    detail.selected = !detail.selected;
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

@end
